package com.hunttown.mes.manage.controller._basic;

import com.hunttown.mes.common.OperateCode;
import com.hunttown.mes.manage.controller.common.AdminBaseClass;
import com.hunttown.mes.manage.controller.common.ModelService;
import com.hunttown.mes.manage.service.TransportRemarkLogManageService;
import com.hunttown.mes.manage.service.AnalysisManageManageService;
import com.hunttown.mes.rpc.domain.AnalysisManageDTO;
import com.hunttown.mes.rpc.domain.TransportRemarkLogDTO;
import com.hunttown.mes.rpc.domain.query.TransportRemarkLogDTOQuery;
import com.hunttown.common.domain.Page;
import com.hunttown.mes.common.utils.JSONUtils;
import com.hunttown.mes.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

import static com.hunttown.mes.common.utils.PageUtils.PagePackage;

/**
 * created by wangjunfu on 2021-01-08 13:49:11
 */
@Controller
@RequestMapping(value = "/basic/remarklog")
public class RemarkLogController {

    private final static Logger logger = LoggerFactory.getLogger(RemarkLogController.class);

    private final TransportRemarkLogManageService remarkLogService;
    private final AnalysisManageManageService manageService;
    private final ModelService modelService;

    @Autowired
    public RemarkLogController(TransportRemarkLogManageService remarkLogService, AnalysisManageManageService manageService, ModelService modelService) {
        this.remarkLogService = remarkLogService;
        this.manageService = manageService;
        this.modelService = modelService;
    }

    //region 数据列表

    /**
     * 首页
     *
     * @param model    model模型
     * @param dtoQuery 查询条件
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(Model model, TransportRemarkLogDTOQuery dtoQuery) {

        if (StringUtils.isNotBlank(dtoQuery.getCreatePeopleCn())) {
            AnalysisManageDTO admin_dto = manageService.getByAdminName(dtoQuery.getCreatePeopleCn().trim());
            if (admin_dto != null) {
                dtoQuery.setCreatePeople(admin_dto.getId());
            }
        }

        dtoQuery.setOrderBy("order by id desc");
        Page<TransportRemarkLogDTO> dataPage = remarkLogService.getForPage(dtoQuery);

        // 实时更新列表信息
        if (dataPage != null && dataPage.getItems().size() > 0) {
            for (TransportRemarkLogDTO item : dataPage.getItems()) {
                item.setTableName(modelService.getChineseName(item.getTableId()));
                item.setCreatePeopleCn(modelService.getManageName(item.getCreatePeople()));
                item.setRemarkLen(item.getRemark() == null ? 0 : item.getRemark().length());
            }
        }

        model.addAttribute("page", dataPage);
        model.addAttribute("PagePackage", PagePackage(dataPage.getPn(), dataPage.getStart(), dataPage.getPageSize(), dataPage.getTotalPages(), dataPage.getTotalItems()));
        model.addAttribute("dtoQuery", dtoQuery);

        modelService.getChineseEnglishPage(model);

        return "/basic/remarklog/index";
    }
    //endregion

    //region 编辑&保存

    /**
     * 编辑
     *
     * @param model model模型
     * @param id    主键id
     * @return
     */
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(Model model, Integer id) {
        id = (id == null ? 0 : id);

        TransportRemarkLogDTO obj;

        if (id > 0) {
            obj = remarkLogService.getById(id);
        } else {
            obj = new TransportRemarkLogDTO();
            obj.setId(0);
        }
        model.addAttribute("Obj", obj);

        return "/basic/remarklog/edit";
    }

    /**
     * 保存 ajax异步
     *
     * @param request sevelet请求
     * @param objDTO  实体类
     * @return
     */
    @RequestMapping(value = "/saveEdit", method = RequestMethod.POST)
    @ResponseBody
    public String saveEditNotify(HttpServletRequest request, TransportRemarkLogDTO objDTO) {

        // 结果返回 结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        try {

            //新增时检验是否唯一
            if (objDTO.getId() == null || objDTO.getId() <= 0) {
                TransportRemarkLogDTOQuery query = new TransportRemarkLogDTOQuery();
                TransportRemarkLogDTO obj = remarkLogService.getByQuery(query);

                if (obj != null && obj.getId() > 0) {
                    //说明此记录已经存在，不能重复插入
                    map = OperateCode.CompositionResult(map, -10, "此记录已存在，请重新输入！");
                    result = JSONUtils.toJSON(map);
                    return result;
                }
            }

            if (objDTO.getId() == null || objDTO.getId() <= 0) {
                //新增
                //设置初始值
                String pin = AdminBaseClass.getPin(request);
                AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
                objDTO.setCreatePeople(curr_obj.getId());
                objDTO.setCreateTime(new Date());
                objDTO.setStopFlag(0);
                objDTO.setDeleteFlag(0);
                objDTO = remarkLogService.insert(objDTO);

                if (objDTO == null || objDTO.getId() <= 0) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }

            } else {
                //更新
                //将不需要更新的字段设置为NULL
                Boolean isNext = remarkLogService.updateInfoById(objDTO);

                if (!isNext) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }
            }

            //操作成功 结果返回
            map = OperateCode.CompositionResult(map, 1);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }
    //endregion

    //region 删除&改变状态

    /**
     * 通过id删除 ajax异步
     *
     * @param id 记录id
     * @return
     */
    @RequestMapping(value = "/deleteById", method = RequestMethod.POST)
    @ResponseBody
    public String deleteNotify(Integer id) {

        // 结果返回结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        if (id == null || id <= 0) {
            map = OperateCode.CompositionResult(map, -10, "请选择要删除的记录！");
            result = JSONUtils.toJSON(map);
            return result;
        }

        try {
            Boolean isNext = remarkLogService.delete(id);
            map = OperateCode.CompositionResult(map, isNext ? 1 : 0);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }

    /**
     * 状态改变 ajax异步
     *
     * @param id     记录id
     * @param status 状态
     * @return
     */
    @RequestMapping(value = "/changeFlag", method = RequestMethod.POST)
    @ResponseBody
    public String openOrStopFlag(Integer id, Integer status) {

        // 结果返回 结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        try {
            Boolean isNext = remarkLogService.changeState(id, status);
            map = OperateCode.CompositionResult(map, isNext ? 1 : 0);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }
    //endregion

    //region 数据查看

    /**
     * 数据查看
     *
     * @param model     model模型
     * @param id        主键id
     * @param tableName 数据库英文表名
     * @return
     */
    @RequestMapping(value = "/show", method = RequestMethod.POST)
    public String show(Model model, Integer id, String tableName) {
        id = (id == null ? 0 : id);

        TransportRemarkLogDTO obj = new TransportRemarkLogDTO();
        obj.setId(id);

        if (id > 0) {
            obj = remarkLogService.getById(id);
        }
        remarkLogService.assembleObjInfo(model, tableName, obj);

        return "show/show-template";
    }

    //endregion

    //region 通过TableID和RecordID获取备注内容

    /**
     * 通过TableID和RecordID获取备注内容
     *
     * @param tableId  数据库表ID
     * @param recordId 记录ID
     * @return map
     */
    @RequestMapping(value = "/getRemarkByTRID", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> getRemarkByTRID(Integer tableId, Integer recordId) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("returnCode", 0);

        TransportRemarkLogDTO dto = remarkLogService.getByTRID(tableId, recordId);
        if (dto == null) {
            //车辆维修委托打印单
            if (tableId == 117 && recordId == 0) {
                map.put("content", "720px");
            } else {
                map.put("content", "");
            }
        } else {
            map.put("content", dto.getRemark());
        }

        map.put("returnCode", 1);
        return map;
    }

    /**
     * 保存备注内容
     *
     * @param tableId  数据库表ID
     * @param recordId 记录ID
     * @param isCover  如果存在相同的记录，是否要覆盖：1是0否
     * @param content  要保存的内容
     * @return map
     */
    @RequestMapping(value = "/saveRemarkByTRID", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> saveRemarkByTRID(HttpServletRequest request, Integer tableId, Integer recordId, Integer isCover, String content) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("returnCode", 0);

        if (tableId == null || tableId <= 0) {
            map.put("returnMessage", "未找到数据表内容！");
            return map;
        }

        if (recordId == null || recordId < 0) {
            recordId = 0;
        }

        if (isCover == null || isCover < 0) {
            isCover = 0;
        }

        String pin = AdminBaseClass.getPin(request);
        AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);

        TransportRemarkLogDTO insert = new TransportRemarkLogDTO();
        insert.setTableId(tableId);
        insert.setRecordId(recordId);
        insert.setRemark(content);

        insert.setRemarkType(0);
        insert.setRemarkReason(0);
        insert.setCreatePeople(curr_obj.getId());
        insert.setCreateTime(new Date());
        insert.setStopFlag(0);
        insert.setDeleteFlag(0);

        //累计插入
        if (isCover == 0) {
            insert = remarkLogService.insert(insert);
            map.put("returnCode", 1);
            return map;
        }

        //数据库无内容，则插入
        TransportRemarkLogDTO dto = remarkLogService.getByTRID(tableId, recordId);
        if (dto == null) {
            insert = remarkLogService.insert(insert);
            map.put("returnCode", 1);
            return map;
        }

        //数据库有内容，则修改
        TransportRemarkLogDTO update = new TransportRemarkLogDTO();
        update.setId(dto.getId());
        update.setRemark(content);
        remarkLogService.updateInfoById(update);

        map.put("returnCode", 1);
        return map;
    }
    //endregion

}